package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Region;
import cn.wolfcode.query.RegionQuery;
import cn.wolfcode.repository.RegionRepository;
import cn.wolfcode.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {



    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);

    }

    @Override
    public List<Region> findAll() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //regionRepository 查询只能对所有数据进行分页
        //template 查询不能直接对数据进行分页 间接分页

        Query query = new Query();

        //totalCount 总记录数
        long totalCount = template.count(query, Region.class);
        if(totalCount == 0){
            return  Page.empty();  //空的分页对象
        }

        //分页参数对象, 参数1 当前页  2 每页显示的条数  3 排序规则  4 排序字段
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageRequest);

        List<Region> list = template.find(query, Region.class);

        return new PageImpl<>(list, pageRequest, totalCount);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(StringUtils.hasLength(region.getId())){
            //有id修改
            //参数个数一致等同于全量更新
            this.update(region);

        }else{
            this.save(region);
        }
    }

    @Override
    public List<Region> queryHotRegion() {
        //状态是热门
        //通过序号排序
        return  regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }

}
